// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

// 云函数入口函数
exports.main = async (event, context) => {
  // const openid = cloud.getWXContext().OPENID

  // if (openid !== event.openid) {
  //   return {
  //     errCode: 401,
  //     errorMsg: '未登录，没有权限！'
  //   }
  // }

  const db = cloud.database()

  const [err, success] = await awaitWrap(
    db.collection('classifyParent').aggregate()
    .lookup({
      from: 'classify',
      localField: 'id',
      foreignField: 'pid',
      as: 'classifyList',
    })
    .end()
  )

  if (success) {
    return {
      data: success.list
    }
  } else {
    return {
      errorMsg: err
    }
  }

}


// await错误处理公共方法
const awaitWrap = (promise) => {
  return promise
    .then(success => [null, success])
    .catch(err => [err, null])
}